import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'


let baseUrl="http://localhost:8090/";
// create an axios instance
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API,
	baseURL: baseUrl,
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
		if (store.getters.token) {
		  config.headers.token = getToken()
		}
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 200) {
          Message({
            message: res.msg || 'Error',
            type: 'error',
            duration: 5 * 1000
          })
        
          // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
          if (res.code === 500 || res.code === 501 || res.code === 503) {
            Message({
              message: res.msg || 'Error',
              type: 'error',
              duration: 5 * 1000
            })
          }
          return Promise.reject(new Error(res.msg || 'Error'))
        } else {
          return res
        }
		Message({
			message: res.msg || 'Success',
			type: 'success',
			duration: 5 * 1000
		})
    },
    error => {
		if (error.response.status === 401 ) {
			Message({
			  message: error.response.data,
			  type: 'error',
			  duration: 3.6 * 1000
			})
				return Promise.reject(error)
		}
        Message({
          message: error.response.data,
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        });
    });
}

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url,data={},params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            params,
            data
        }).then(response => {
            resolve(response);
        });
    });
}

export default service
